<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编码" prop="itemCode">
        <el-input v-model="queryParams.itemCode" placeholder="请输入商品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="拍品标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入拍品标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="拍卖状态" prop="auctionStatus">
        <el-select v-model="queryParams.auctionStatus" placeholder="请选择拍卖状态" clearable>
          <el-option label="竞拍中" value="ongoing" />
          <el-option label="已结束" value="ended" />
          <el-option label="已成交" value="sold" />
          <el-option label="流拍" value="unsold" />
        </el-select>
      </el-form-item>
      <el-form-item label="推荐" prop="tuijian">
        <el-select v-model="queryParams.tuijian" placeholder="请选择推荐状态" clearable>
          <el-option label="推荐" value="1" />
          <el-option label="不推荐" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:auction:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" height="70vh" :data="auctionList" @selection-change="handleSelectionChange">
      <el-table-column label="商品编码" align="center" prop="itemCode" width="120" />
      <el-table-column label="拍品标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="版本信息" align="center" prop="versionInfo" width="150" :show-overflow-tooltip="true" /> -->
      <el-table-column label="商品标签" align="center" prop="tags" width="100">
        <template slot-scope="scope">
          <el-tag v-for="item in scope.row.tags" :key="item" style="margin-right: 5px;">{{ tags.find(t => t.id ==
      item).name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评级卡" align="center" prop="isRated" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isRated" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评级等级" align="center" prop="ratingGrade" width="100" />
      <!-- <el-table-column label="连号" align="center" prop="isConsecutive" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isConsecutive" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="起拍价" align="center" prop="startPrice" width="100">
        <template slot-scope="scope">
          ¥{{ scope.row.startPrice }}
        </template>
      </el-table-column>
      <el-table-column label="当前拍卖价格" align="center" prop="currentPrice" width="100">
        <template slot-scope="scope">
          ¥{{ scope.row.currentPrice }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="拍卖状态" align="center" prop="auctionStatusLabel" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.auctionStatusLabel == 'ongoing'" type="success">竞拍中</el-tag>
          <el-tag v-else-if="scope.row.auctionStatusLabel == 'ended'" type="info">已结束</el-tag>
          <el-tag v-else-if="scope.row.auctionStatusLabel == 'sold'" type="warning">已成交</el-tag>
          <el-tag v-else-if="scope.row.auctionStatusLabel == 'unsold'" type="danger">流拍</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="推荐" align="center" prop="tuijian" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.tuijian" :active-value="1" :inactive-value="0"
            @change="handleTuijianChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="封面图片" align="center" prop="coverImage" width="100">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.coverImage" :src="scope.row.coverImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:auction:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:auction:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改竞拍对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="请输入商品编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拍品标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入拍品标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品标签" prop="tags" class="form-item">
              <el-select v-model="form.tags" multiple="" placeholder="请选择商品标签" class="full-width-input">
                <el-option v-for="item in tags" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评级等级" prop="ratingGrade">
              <el-input v-model="form.ratingGrade" placeholder="请输入评级等级" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="请选择对应专区" prop="mokId">
              <el-select v-model="form.mokId" placeholder="请选择对应专区" @change="handleJpzqChange" clearable>
                <el-option v-for="item in jpzqOptions" :label="item.title" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="false">
            <el-form-item label="对应专区标题" prop="mokTitle">
              <el-input v-model="form.mokTitle" placeholder="对应专区标题" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否为评级卡" prop="isRated">
              <el-radio-group v-model="form.isRated">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="是否连号" prop="isConsecutive">
              <el-radio-group v-model="form.isConsecutive">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="起拍价" prop="startPrice">
              <el-input-number v-model="form.startPrice" :precision="2" :min="400" placeholder="请输入起拍价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前拍卖价格" prop="currentPrice">
              <el-input-number v-model="form.currentPrice" disabled :precision="2" :min="0" placeholder="请输入当前拍卖价格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择开始时间"
                value-format="yyyy-MM-dd HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择结束时间"
                value-format="yyyy-MM-dd HH:mm:ss" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="拍卖状态" prop="auctionStatusLabel">
              <el-select v-model="form.auctionStatusLabel" placeholder="请选择拍卖状态" disabled>
                <el-option label="竞拍中" value="ongoing" />
                <el-option label="已结束" value="ended" />
                <el-option label="已成交" value="sold" />
                <el-option label="流拍" value="unsold" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否推荐" prop="tuijian">
              <el-switch v-model="form.tuijian" :active-value="1" :inactive-value="0" active-text="推荐"
                inactive-text="不推荐">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="封面图片" prop="coverImage">
          <image-upload1 v-model="form.coverImage" :limit="1" />
        </el-form-item>
        <el-form-item label="缩略图" prop="thumbnailImage">
          <image-upload1 v-model="form.thumbnailImage" :limit="8" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入商品描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAuctionItem, addCardAuctionItem, deleteItemBId, listAuctionMok } from '@/api/system/auction'
import ImageUpload1 from "@/components/ImageUpload/index1"

export default {
  name: "Auction",
  components: { ImageUpload1 },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 竞拍表格数据
      auctionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: null,
        title: null,
        status: null,
        tuijian: null
      },
      // 表单参数
      form: {},
      // jpzq选项列表
      jpzqOptions: [],
      // 表单校验
      rules: {
        itemCode: [
          { required: false, message: "商品编码不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "拍品标题不能为空", trigger: "blur" }
        ],
        startPrice: [
          { required: true, message: "起拍价不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        tags: [
          { required: true, message: "商品标签不能为空", trigger: "change" }
        ]
      },
      tags: [
        {
          id: "1",
          name: 'PSA10'
        },
        {
          id: "2",
          name: 'PSA鉴定'
        },
        {
          id: "3",
          name: '限定'
        },
        {
          id: "4",
          name: 'NEW'
        },
        {
          id: "5",
          name: '折扣'
        },
      ]
    };
  },
  created() {
    this.getList();
    this.getJpzqOptions();
  },
  methods: {
    /** 查询竞拍列表 */
    getList() {
      this.loading = true;
      listAuctionItem(this.queryParams).then(response => {
        this.auctionList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 获取jpzq选项列表 */
    getJpzqOptions() {
      const params = {
        pageSize: -1,
        pageNum: 1,
        active: 1
      };
      listAuctionMok(params).then(response => {
        this.jpzqOptions = response.data || [];
      }).catch(() => {
        this.jpzqOptions = [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        itemCode: null,
        title: null,
        tags: [],
        isRated: 0,
        ratingGrade: null,
        // isConsecutive: false,
        startTime: null,
        startPrice: 400,
        currentPrice: null,
        endTime: null,
        status: 1,
        coverImage: null,
        thumbnailImage: [],
        tuijian: 0,
        description: null,
        mokId: null,
        mokTitle: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加竞拍";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      // 这里应该根据id获取详细信息，现在直接使用row数据
      this.form = Object.assign({}, row);
      this.open = true;
      this.title = "修改竞拍";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form.thumbnailImage);

          this.form.isRated = this.form.isRated ? 1 : 0;
          if (typeof this.form.thumbnailImage === 'string') {
            this.form.thumbnailImage = this.form.thumbnailImage.split(',');
          }

          if (this.form.id != null) {
            // 修改操作 - 这里可以添加更新API调用
            addCardAuctionItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增操作
            addCardAuctionItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除竞拍编号为"' + ids + '"的数据项？').then(() => {
        return deleteItemBId(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 处理推荐状态变化 */
    handleTuijianChange(row) {
      // 可以在这里调用更新API
      addCardAuctionItem(row).then(res => {
        // this.$modal.msgSuccess("推荐状态更新成功");
        this.getList();
      });

    },
    /** 处理jpzq选择变化 */
    handleJpzqChange(value) {
      if (value) {
        const selectedJpzq = this.jpzqOptions.find(item => item.id === value);
        if (selectedJpzq) {
          this.form.mokTitle = selectedJpzq.title;
        }
      } else {
        this.form.mokTitle = null;
      }
    },
    // 时间格式化
    parseTime(time, cFormat) {
      if (arguments.length === 0 || !time) {
        return null
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string')) {
          if ((/^[0-9]+$/.test(time))) {
            // support "1548221490638"
            time = parseInt(time)
          } else {
            // support safari
            // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
            time = time.replace(new RegExp(/-/gm), '/')
          }
        }

        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        return value.toString().padStart(2, '0')
      })
      return time_str
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: right;
}
</style>
